import { PersistStorage, StorageValue } from "zustand/middleware";
import {
  getStorageSync,
  setStorageSync,
  removeStorageSync,
} from "@tarojs/taro";

// 创建一个通用的 storage 工具函数
export const createStorage = <T>(): PersistStorage<T> => ({
  getItem: async (name: string): Promise<StorageValue<T> | null> => {
    try {
      const value = getStorageSync(name);
      return value ? value : null;
    } catch (e) {
      console.error("获取存储失败：", e);
      return null;
    }
  },
  setItem: async (name: string, value: StorageValue<T>): Promise<void> => {
    try {
      setStorageSync(name, value);
    } catch (e) {
      console.error("设置存储失败：", e);
    }
  },
  removeItem: async (name: string): Promise<void> => {
    try {
      removeStorageSync(name);
    } catch (e) {
      console.error("删除存储失败：", e);
    }
  },
});
